//
//  BookcaseView.m
//  ebook
//
//  Created by 吴超飞 on 16/3/4.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "BookcaseView.h"
#import "UIImage+RTTint.h"
#import "Bookmark.h"
#import "FmdbAccess.h"
#import "FileManager.h"
#import "DownloadManager.h"

#define DeleteBtnTag 100
#define CellTag 1000

#define AddBtnTag 9999

@interface BookcaseView()

@property (nonatomic,strong) UITapGestureRecognizer *tapGestureRecognizer ;

@end

@implementation BookcaseView

-(instancetype)initWithBookArray:(NSMutableArray *)array frame:(CGRect)frame{
    
    self.books = array;
    self = [super initWithFrame:frame];
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    
    //底板
    UIView* view = [[UIView alloc] initWithFrame: frame];
    view.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseViewBaseboard_Color");
    [self addSubview:view];
    
    self.books = array;
    float imgWidth = ImageWidth, imgHeight = ImageHeight;
    
    if (self) {
        
        float x = 0.0,y = 0.0;
        for (int i = 0; i<array.count + 1; i++) {
            int line , index;
            
            if (isIpad) {
                line = i/4;
                index = i%4;
            } else {
                line = i/3;
                index = i%3;
            }
            
            CGRect cellframe = CGRectZero;
            x = SpaceOut + (SpaceIn + imgWidth)*index;
            y = SpaceOut + (SpaceIn + imgHeight+35)*line;
            
            cellframe = CGRectMake(x, y, imgWidth, imgHeight+35);
            
            if (i<array.count) {
                
                Book *book = [array objectAtIndex:i];
                BookcaseCellView *cellView = [[BookcaseCellView alloc] initWithFrame:cellframe];
                cellView.delegate = self;
                cellView.deleteBtn.tag = DeleteBtnTag + i;
                cellView.tag = CellTag + i;
                [cellView setBook:book];
                [self addSubview:cellView];
            }else{
                
                UIView *addView = [[UIView alloc] initWithFrame:CGRectMake( x, y, imgWidth, imgHeight)];
                addView.tag = AddBtnTag;
                UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake( 0, 0, imgWidth, imgHeight)];
                [addBtn setBackgroundImage:[UIImage imageNamed:@"addbook_nl"] forState:UIControlStateNormal];
                [addBtn setBackgroundImage:[UIImage imageNamed:@"addbook_hl"]forState:UIControlStateHighlighted];
                [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                [addView addSubview:addBtn];
                [self addSubview:addView];
            }
        }
        
        float contentHeight = y + imgHeight + 30 +20;
        self.contentSize = CGSizeMake(self.frame.size.width, contentHeight < self.frame.size.height?self.frame.size.height+10 : contentHeight);
    }
    
    view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, self.contentSize.height * 2);
    
    /*也添加cell的手势，以便用户点击背景也能操作*/
    //长按手势
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressGestureRecognizer:)];
    [self addGestureRecognizer:longGesture];
    
    //添加点击手势事件
    _tapGestureRecognizer = [[UITapGestureRecognizer  alloc] initWithTarget:self action:@selector(tapOnContentView:)];
    _tapGestureRecognizer.delegate = self;
    [self addGestureRecognizer:_tapGestureRecognizer];
    
    return self;
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([touch.view isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return YES;
}

- (void)LongPressGestureRecognizer:(UIGestureRecognizer *)gr
{
    [self bookcaseCellView:nil longPressGestureRecognizer:gr];
}

- (void)tapOnContentView:(UITapGestureRecognizer *)tapGestureRecognizer
{
    [self bookcaseCellView:nil tapedWhileIsEdit:YES];
}

-(void)addBtnClick:(UIButton *)btn{
    
    if ([self.bookDelegate respondsToSelector:@selector(bookcaseViewClickAddBook:)]) {
        [self.bookDelegate bookcaseViewClickAddBook:self];
    }
}

#pragma mark - BookcaseCellViewDelegate
-(void)bookcaseCellView:(BookcaseCellView *)cell deleteBtnClick:(UIButton *)btn{
    
    if (_books.count < (btn.tag-DeleteBtnTag)) return;
    Book *book = [_books objectAtIndex:(btn.tag - DeleteBtnTag)];
    if ([self.bookDelegate respondsToSelector:@selector(bookcaseView:deleteBook:complete:)]) {
        [self.bookDelegate bookcaseView:self deleteBook:book complete:^(BOOL suc) {
            if(suc)[self buttonChange:btn];
        }];
    }
}

-(void)bookcaseCellView:(BookcaseCellView *)cell longPressGestureRecognizer:(UIGestureRecognizer *)gr{
    
    for (UIView *sub in self.subviews) {
        if ([sub isKindOfClass:[BookcaseCellView class]]) {
            ((BookcaseCellView*)sub).isCanDelete = YES;
        }
    }
    
    if ([self.bookDelegate respondsToSelector:@selector(bookcaseView:isEditing:)]) {
        [self.bookDelegate bookcaseView:self isEditing:YES];
    }
}

-(void)bookcaseCellView:(BookcaseCellView *)cell tapedWhileIsEdit:(BOOL)isEdit{
    
    if (isEdit) {//正在编辑，点击变为正常态
        for (UIView *sub in self.subviews) {
            if ([sub isKindOfClass:[BookcaseCellView class]]) {
                ((BookcaseCellView*)sub).isCanDelete = NO;
            }
        }
        if ([self.bookDelegate respondsToSelector:@selector(bookcaseView:isEditing:)]) {
            [self.bookDelegate bookcaseView:self isEditing:NO];
        }
    }else{//传递点击事件
        if (_books.count < cell.tag-CellTag) return;
        Book *book = [_books objectAtIndex:(cell.tag - CellTag)];
        if ([self.bookDelegate respondsToSelector:@selector(bookcaseView:clickBookItem:)]) {
            [self.bookDelegate bookcaseView:self clickBookItem:book];
        }
    }
}

-(void)buttonChange:(UIButton*)sender
{
    NSArray *viewsall= self.subviews;
    NSMutableArray *views = [NSMutableArray array];
    [viewsall enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj isKindOfClass:[BookcaseCellView class]]||obj.tag == AddBtnTag)
            [views addObject:obj];
    }];
    
    __block CGRect newframe = CGRectZero;
    NSInteger index = sender.tag - DeleteBtnTag;
    for (NSInteger i = index; i < [_books count]+1; i++)
    {
        UIView *obj = views.count>i?[views objectAtIndex:i]:nil;
        __block CGRect nextframe = obj.frame;
        if (i == index)
        {
            //删除这个view
            [obj removeFromSuperview];
        }
        else
        {
            for (UIView *v in obj.subviews)
            {
                //把每个按钮的tag从重设置
                if ([v isMemberOfClass:[UIButton class]])
                {
                    v.tag = i + DeleteBtnTag - 1;
                    break;
                }
            }
            
            if([obj isMemberOfClass:[BookcaseCellView class]])
                obj.tag -=1 ;
            
            //并且位置动画改变
            [UIView animateWithDuration:0.6 animations:^
             {
                 obj.frame = newframe;
             } completion:^(BOOL finished)
             {
             }];
        }
        //记住上一个view的位置
        newframe = nextframe;
    }
    
    //数组移除
    if(index<_books.count)
        [_books removeObjectAtIndex:index];
}

-(void)setIsEdit:(BOOL)isEdit{
    
    _isEdit = isEdit;
    for (UIView *sub in self.subviews) {
        if ([sub isKindOfClass:[BookcaseCellView class]]) {
            ((BookcaseCellView*)sub).isCanDelete = isEdit;
        }
    }
}

//更新阅读百分比
-(void)updateBookcaseReadpercent:(Book *)book{
    float totoalCount = [book.chaptercount floatValue];
    float percent = totoalCount==0?0:(float)[book.rposition intValue]*100/totoalCount;
    NSString *percentStr = [NSString stringWithFormat:@"已读%.1f%\%", percent];
    [self cellOfBook:book].readedPercentLabel.text = percentStr;
}

//更新下载状态
- (void)updateBookcaseDownstatus:(NSDictionary *)dic {
    
    [_books enumerateObjectsUsingBlock:^(Book *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        BookcaseCellView *bookView = [self cellOfBook:obj];
        if ([obj.bookid integerValue] == [dic[@"bookId"] integerValue]) {//当前正在下载这本书
            
            //下载百分比
            float percent = [dic[@"percent"] floatValue];
            BOOL exist = [dic[@"exist"] boolValue];
            if (!exist) {
                if (percent > 0.999f) {
                    int totoal = [obj.chaptercount intValue];
                    float readPercent = totoal==0?0:(float)[obj.rposition intValue]/totoal;
                    
                    if(readPercent==0)
                        readPercent=0.001;
                    
                    NSString *rpstr = ([@"0.001" isEqualToString:[NSString stringWithFormat:@"%0.3f", readPercent]]?@"未读":[NSString stringWithFormat:@"已读%.1f%\%", readPercent]);
                    bookView.readedPercentLabel.text = rpstr;
                    [bookView.progressView displayOperationDidFinishAnimation];
                    bookView.progressView.progress = 1.0;
                } else {
                    NSString *dpstr = [NSString stringWithFormat:@"下载%.1f%\%", percent*100];
                    bookView.readedPercentLabel.text = dpstr;
                    bookView.progressView.hidden = NO;
                    bookView.progressView.progress = percent;
                }
            }
            
        }else if([[DownloadManager shareInstance] downloadQuequOfBook:obj.bookid]){//在下载队列中
            
            bookView.readedPercentLabel.text = @"等待下载";
            bookView.progressView.hidden = NO;
        }
    }];
}

- (BookcaseCellView *)cellOfBook:(Book *) book {
    
    __block Book *bookInlist = book;
    [_books enumerateObjectsUsingBlock:^(Book *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([book.bookid integerValue] == [obj.bookid integerValue]) {
            bookInlist = obj;
            *stop = YES;
        }
    }];
    
    NSInteger tag = [_books indexOfObject:bookInlist]+CellTag;
    //遍历cell找到当前下载的图书，如果正在下载：已读百分比－－>下载百分比   缓存百分比显示
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[BookcaseCellView class]]) {
            BookcaseCellView *cellView = (BookcaseCellView *)view;
            if (cellView.tag == tag) {
                return cellView;
                //                cellView.readedPercentLabel.text = text;
            }
        }
    }
    return nil;
}

- (void)updateBookcaseNetworkState:(BOOL)isNetConnected {
    
    if (!isNetConnected) {
        UIView *warmView = [[UIView alloc] init];
        warmView.frame = CGRectMake(0, (CGRectGetMinY(self.subviews[1].frame)-44)/2, MTScreenW, 44);
        warmView.backgroundColor = MTColor(255, 223, 224, 1);
        warmView.tag = 1223;
        [self addSubview:warmView];
        
        UIImage *img = [UIImage imageNamed:@"notification_error"];
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.frame = CGRectMake(20, (warmView.height-img.size.height)/2, img.size.width, img.size.height);
        imgView.image = img;
        [warmView addSubview:imgView];
        
        UILabel *warmLabel = [[UILabel alloc] init];
        warmLabel.frame = CGRectMake(CGRectGetMaxX(imgView.frame)+7, 0, MTScreenW-CGRectGetMaxX(imgView.frame)-10, 44);
        warmLabel.text = @"当前网络不可用，请检查你的网络设置";
        warmLabel.textColor = [UIColor darkGrayColor];
        warmLabel.font = [UIFont systemFontOfSize:14.0];
        [warmView addSubview:warmLabel];
        
    } else {
        UIView *view = [self viewWithTag:1223];
        if (view) {
            [view removeFromSuperview];
            view = nil;
        }
    }
}

-(void)dealloc{
    _tapGestureRecognizer.delegate = nil;
    _tapGestureRecognizer = nil;
}

@end
